package xyz.scootaloo.kami.server

import io.vertx.kotlin.coroutines.CoroutineVerticle
import xyz.scootaloo.kami.server.standard.getLogger
import xyz.scootaloo.kami.server.service.StageEventEmitter
import xyz.scootaloo.kami.server.verticle.MainDeployer
import xyz.scootaloo.kami.server.verticle.liteComponents

/**
 * 程序入口
 *
 * @author flutterdash@qq.com
 * @since 2021/12/30 23:43
 */
object MainVerticle : CoroutineVerticle() {

    val deploymentId get() = deploymentID

    private val log by lazy { getLogger() }

    override suspend fun start() {
        StageEventEmitter.beforeVerticleDeploy()
        safeCall(deploySuccessMessagePair()) {
            MainDeployer.deploy(vertx, liteComponents())
            StageEventEmitter.afterApplicationStarted()
        }
    }

    override suspend fun stop() {
        safeCall(undeployFailureMessagePair()) {
            MainDeployer.undeploy()
        }
    }

    private suspend fun safeCall(msgPair: Pair<String, String>, block: suspend () -> Unit) = try {
        block()
        log.info(msgPair.first)
    } catch (e: Throwable) {
        log.error("${msgPair.second} => ${e.message}", e)
    }

    private fun deploySuccessMessagePair() = "部署应用成功" to "部署应用失败"
    private fun undeployFailureMessagePair() = "取消部署成功" to "取消部署失败"
}